package com.kodcu.data.dao.jpa;

import com.kodcu.data.dao.interfaces.EpostaDao;
import com.kodcu.data.dataobjects.Eposta;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;
import java.util.List;


/**
 * @author Richard Wilkinson - richard.wilkinson@jweekend.com
 */
@Repository
public class EpostaDaoJPAImp extends AbstractDaoJPAImpl<Eposta> implements EpostaDao {

    public EpostaDaoJPAImp() {
        super(Eposta.class);
    }

    @Transactional
    public List<Eposta> findAll() {
        return getJpaTemplate().execute(new JpaCallback<List<Eposta>>() {
            public List<Eposta> doInJpa(EntityManager em) throws PersistenceException {
                TypedQuery<Eposta> query = em.createQuery("select e from Eposta e", Eposta.class);
                return query.getResultList();
            }
        });
    }

    @Transactional
    public boolean find(final Eposta e) {
        return getJpaTemplate().execute(new JpaCallback<Boolean>() {
            public Boolean doInJpa(EntityManager em) throws PersistenceException {
                TypedQuery<Eposta> query = em.createQuery("select e from Eposta e where e.eposta = :eposta "
                        , Eposta.class);
                query.setParameter("eposta", e.getEposta());
               
                try {
                    Eposta result = query.getSingleResult();
                    if (result != null) {
                        return true; // found
                    } else {
                        return false;  // not found
                    }
                } catch (NoResultException ex) {

                    return false;  // not found
                }
            }
        });
    }

    @Transactional
    public int countAll() {
        return getJpaTemplate().execute(new JpaCallback<Integer>() {

            public Integer doInJpa(EntityManager em) throws PersistenceException {
                TypedQuery<Long> query = em.createQuery("select count (e) from Eposta e", Long.class);
                return (query.getSingleResult()).intValue();
            }
        });

    }
}
